package com.gdhz.xiaohengqin.service;

import com.gdhz.xiaohengqin.model.ErJingWanVo;
import com.gdhz.xiaohengqin.reservation.constants.TeleOneConstant;
import com.gdhz.xiaohengqin.reservation.model.entity.ReservationRecord;
import com.gdhz.xiaohengqin.reservation.service.ReservationRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * 二井湾至智慧规建服务层
 *
 * @author Swallows
 * @date 2025-08-06 16:13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ErJingWanService {

    private final ReservationRecordService recordService;

    public Mono<ErJingWanVo<ReservationRecord>> pushQrCodeNotification(String url) {
        return recordService.verifyByQrCode(url, TeleOneConstant.ER_JING_WAN_TOKEN_PROD)
                .flatMap(record -> {
                    log.info("【二井湾】智慧规建返回的预约结果，状态码: {}, 消息: {}", record.getCode(), record.getMessage());
                    if (record.getCode().equals(TeleOneConstant.CODE_10000000)) {
                        return recordService.verifyById(record.getData().getId())
                                .flatMap(verificationResult -> {
                                    if ("1".equals(verificationResult.getData().getVisitStatus()))  {
                                        log.info(" 状态合法，触发开门");
                                        ErJingWanVo<ReservationRecord> response = new ErJingWanVo<>();
                                        response.setCode(0);
                                        response.setMessage(record.getMessage());
                                        response.setData(record.getData());
                                        return Mono.just(response);
                                    } else {
                                        log.error(" 状态非法: visitStatus={}", verificationResult.getData().getVisitStatus());
                                        return Mono.empty();
                                    }
                                });
                    } else {
                        ErJingWanVo<ReservationRecord> errorResponse = new ErJingWanVo<>();
                        errorResponse.setCode(1001);
                        errorResponse.setMessage("Error: " + record.getMessage());
                        return Mono.just(errorResponse);
                    }
                })
                .onErrorResume(e -> {
                    ErJingWanVo<ReservationRecord> errorResponse = new ErJingWanVo<>();
                    errorResponse.setCode(1001);
                    errorResponse.setMessage("Error: " + e.getMessage());
                    return Mono.just(errorResponse);
                });

    }
}
